﻿using AbpVnext_Module.Iservice;
using AbpVnext_Module.Repository;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Account.Settings;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.Settings;
using Volo.Abp.Application.Services;
using Microsoft.Extensions.Options;
using Volo.Abp.Validation;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Auditing;

namespace AbpVnext_Module.Service
{
    /// <summary>
    /// ApplicationService 基础封装工具类
    /// </summary>
    [Dependency(ServiceLifetime.Transient)]
    public class ProductService : ApplicationService, IProductService
    {
        //public IProductImageRepository ProductImageRepository { get; set; }

        protected SignInManager<Volo.Abp.Identity.IdentityUser> SignInManager { get; }
        protected IdentityUserManager UserManager { get; }

        protected ISettingProvider SettingProvider { get; }
        protected IdentitySecurityLogManager IdentitySecurityLogManager { get; }
        protected IOptions<IdentityOptions> IdentityOptions { get; }
        protected IdentityDynamicClaimsPrincipalContributorCache IdentityDynamicClaimsPrincipalContributorCache { get; }

        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="userLoginInfo"></param>
        [HttpPost]
        public async Task<string> LoginTest(UserLoginInfo login)
        {
            await CheckLocalLoginAsync();

            ValidateLoginInfo(login);

            await ReplaceEmailToUsernameOfInputIfNeeds(login);

            await IdentityOptions.SetAsync();

            var signInResult = await SignInManager.PasswordSignInAsync(
                login.UserNameOrEmailAddress,
                login.Password,
                login.RememberMe,
                true
            );

            await IdentitySecurityLogManager.SaveAsync(new IdentitySecurityLogContext()
            {
                Identity = IdentitySecurityLogIdentityConsts.Identity,
                //Action = signInResult.ToIdentitySecurityLogAction(),
                UserName = login.UserNameOrEmailAddress
            });

            if (signInResult.Succeeded)
            {
                var user = await UserManager.FindByNameAsync(login.UserNameOrEmailAddress);
                if (user != null)
                {
                    // Clear the dynamic claims cache.
                    await IdentityDynamicClaimsPrincipalContributorCache.ClearAsync(user.Id, user.TenantId);
                }
            }

            //return GetAbpLoginResult(signInResult);
            return "";
        }

        //private static AbpLoginResult GetAbpLoginResult(SignInResult result)
        //{
        //    if (result.IsLockedOut)
        //    {
        //        return new AbpLoginResult(LoginResultType.LockedOut);
        //    }

        //    if (result.RequiresTwoFactor)
        //    {
        //        return new AbpLoginResult(LoginResultType.RequiresTwoFactor);
        //    }

        //    if (result.IsNotAllowed)
        //    {
        //        return new AbpLoginResult(LoginResultType.NotAllowed);
        //    }

        //    if (!result.Succeeded)
        //    {
        //        return new AbpLoginResult(LoginResultType.InvalidUserNameOrPassword);
        //    }

        //    return new AbpLoginResult(LoginResultType.Success);
        //}

        protected virtual async Task ReplaceEmailToUsernameOfInputIfNeeds(UserLoginInfo login)
        {
            if (!ValidationHelper.IsValidEmailAddress(login.UserNameOrEmailAddress))
            {
                return;
            }

            var userByUsername = await UserManager.FindByNameAsync(login.UserNameOrEmailAddress);
            if (userByUsername != null)
            {
                return;
            }

            var userByEmail = await UserManager.FindByEmailAsync(login.UserNameOrEmailAddress);
            if (userByEmail == null)
            {
                return;
            }

            login.UserNameOrEmailAddress = userByEmail.UserName;
        }

        protected virtual void ValidateLoginInfo(UserLoginInfo login)
        {
            if (login == null)
            {
                throw new ArgumentException(nameof(login));
            }

            if (login.UserNameOrEmailAddress.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(login.UserNameOrEmailAddress));
            }

            if (login.Password.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(login.Password));
            }
        }

        protected virtual async Task CheckLocalLoginAsync()
        {
            if (!await SettingProvider.IsTrueAsync(AccountSettingNames.EnableLocalLogin))
            {
                throw new UserFriendlyException(L["LocalLoginDisabledMessage"]);
            }
        }

        public ProductService()
        {

        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public string InsertProduct(Product product)
        {
            #region  普通添加
            //Context.Product.Add(product);
            //Context.SaveChanges();
            return "添加成功";
            #endregion

            #region  abp仓储层添加
            //ProductImage image = new ProductImage();
            //image.Url = product.Name;
            //image.ProductId = 10;
            //var productImage = ProductImageRepository.InsertAsync(image);
            //return "添加成功";
            #endregion
        }
    }

    public class UserLoginInfo
    {
        [Required]
        [StringLength(255)]
        public string UserNameOrEmailAddress { get; set; }

        [Required]
        [StringLength(32)]
        [DataType(DataType.Password)]
        [DisableAuditing]
        public string Password { get; set; }

        public bool RememberMe { get; set; }
    }
}
